﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using NAudio.Wave;

namespace BToolkit
{
    /// <summary>
    /// 播放APP外部的音效
    /// </summary>
    public class OutAudioPlayer : MonoBehaviour
    {
        static OutAudioPlayer _BGMInstance;
        static OutAudioPlayer _singleInstance;
        static Dictionary<string, AudioClip> audios = new Dictionary<string, AudioClip>();
        MusicPlayer _musicPlayer;

        public static void PlayBGM(string path, bool resume, bool loop)
        {
            if (!_BGMInstance)
            {
                GameObject mgr = GameObject.Find("BGMPlayer");
                if (mgr)
                {
                    _BGMInstance = mgr.GetComponent<OutAudioPlayer>();
                }
                else
                {
                    GameObject go = new GameObject("BGMPlayer");
                    DontDestroyOnLoad(go);
                    _BGMInstance = go.AddComponent<OutAudioPlayer>();
                }
            }
            _BGMInstance.PlayLocalAudio(path, resume, loop);
        }

        public static void PauseBGM()
        {
            if (_BGMInstance && _BGMInstance._musicPlayer) _BGMInstance._musicPlayer.Pause();
        }

        public static void ResumeBGM()
        {
            if (_BGMInstance && _BGMInstance._musicPlayer) _BGMInstance._musicPlayer.Resume();
        }

        public static void PlaySingleSound(string path, bool resume, bool loop)
        {
            if (!_singleInstance)
            {
                GameObject single = GameObject.Find("SingleSoundPlayer");
                if (single)
                {
                    _singleInstance = single.GetComponent<OutAudioPlayer>();
                }
                else
                {
                    GameObject go = new GameObject("SingleSoundPlayer");
                    DontDestroyOnLoad(go);
                    _singleInstance = go.AddComponent<OutAudioPlayer>();
                }
            }
            _singleInstance.PlayLocalAudio(path, resume, loop);
        }


        private void Awake()
        {
            _musicPlayer = MusicPlayer.NewInstance();
        }

        /// <summary>
        /// 播放本地磁盘的音乐
        /// </summary>
        void PlayLocalAudio(string path, bool resume, bool loop)
        {
            if (audios.ContainsKey(path))
            {
                _musicPlayer.Play(0, audios[path], resume, loop);
            }
            else
            {
                StartCoroutine(LoadAndPlayAudio(path, resume, loop));
            }
        }

        /// <summary>
        /// 停止播放
        /// </summary>
        public void StopAudio()
        {
            _musicPlayer.Stop();
        }

        IEnumerator LoadAndPlayAudio(string path, bool resume, bool loop)
        {

            if (!path.Contains("."))
            {
                string filePath = path.Substring(0, path.LastIndexOf('/'));
                if (!Directory.Exists(filePath))
                {
                    Debug.LogError("文件夹[" + filePath + "]不存在");
                    yield break;
                }
                string[] filePaths = Directory.GetFiles(filePath, "*", SearchOption.TopDirectoryOnly);
                for (int i = 0; i < filePaths.Length; i++)
                {
                    string fullPath = filePaths[i].Replace("\\", "/");
                    if (fullPath.StartsWith(path))
                    {
                        path = fullPath;
                        break;
                    }
                }
            }
            if (path.EndsWith(".mp3"))
            {
                //将MP3转换成WAV
                string wavPath = path.Replace(".mp3", ".wav");
                if (!File.Exists(wavPath))
                {
                    using (var audioStrem = new Mp3FileReader(path))
                    {
                        WaveFileWriter.CreateWaveFile(wavPath, audioStrem);
                    }
                }
                path = wavPath;
            }
            UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip("file://" + path, AudioType.UNKNOWN);
            yield return request.SendWebRequest();
            if (request.error == null)
            {
                AudioClip clip = DownloadHandlerAudioClip.GetContent(request);
                if (clip)
                {
                    audios[path] = clip;
                    _musicPlayer.Play(0, clip, resume, loop);
                }
            }
        }

    }
}